package com.molyfun.parents.fragment.main;

import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.course.CoursePickActivity;
import com.molyfun.parents.activity.coursecenter.model.SubjectListResponse;
import com.molyfun.parents.activity.store.adapter.ProductHeaderAdapter;
import com.molyfun.parents.fragment.BaseFragment;
import com.molyfun.parents.rest.RestClient;
import com.molyfun.parents.rest.bean.TeamListResponse;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.uievent.UIEventListener;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.TwoTabBar;
import com.molyfun.parents.view.swipeRefreshLayout.SwipeRefreshLayout;

import java.lang.reflect.Field;

import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by ZhaoWei on 2016/12/5.
 * 首页
 */

public class ClassCenterFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, SwipeRefreshLayout.OnLoadListener,
        UIEventListener, ProductHeaderAdapter.ClassCenterFragmentInterface {

    RecyclerView mRecyclerView;
    SwipeRefreshLayout mSwipeRefreshLayout;
    LinearLayout mEmptyLayout;

    private LinearLayoutManager mLayoutManager;
    private ProductHeaderAdapter mProductAdapter;
    private int mCurrentPage = RestClient.DEFAULT_PAGE;
    private boolean mHasMoreData = true;

    private CoursePickActivity.CoursePickStorage mCoursePickStorage;
    private int mCurrentTab = TwoTabBar.TwoTabChooseTab.BAR_ONE;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_class_center, container, false);
        ButterKnife.inject(this, view);

//        mTwoTabBar = (TwoTabBar) view.findViewById(R.id.two_tab_bar);
//        mTwoTabBar.initData("公开课", "一对一");
//        mMsgIcon.setOnClickListener(this);
//        mSearch.setOnClickListener(this);
//        mPickBtn.setOnClickListener(this);


        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
        mEmptyLayout = (LinearLayout) view.findViewById(R.id.empty_layout);

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setOnLoadListener(this);
        mSwipeRefreshLayout.setTopColor(R.color.refresh_color_01, R.color.refresh_color_02,
                R.color.refresh_color_02, R.color.refresh_color_01);
        mSwipeRefreshLayout.setBottomColor(R.color.color_transparent, R.color.color_transparent,
                R.color.color_transparent, R.color.color_transparent);
        mSwipeRefreshLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        mSwipeRefreshLayout.setLoadNoFull(true);

        try {
            Field f = null;
            f = SwipeRefreshLayout.class.getDeclaredField("mTouchSlop");
            f.setAccessible(true);
            f.set(mSwipeRefreshLayout, 150);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        mLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mProductAdapter = new ProductHeaderAdapter(getContext(), this);
        mRecyclerView.setAdapter(mProductAdapter);

        loadData(RestClient.DEFAULT_PAGE, RestClient.DEFAULT_PAGE_SIZE, true);
        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_COURSE_PICK, this);

        return view;
    }

    @Override
    public void onTwoBarClick(int chooseTab) {
        switch (chooseTab){
            case TwoTabBar.TwoTabChooseTab.BAR_ONE:
                mCurrentTab = TwoTabBar.TwoTabChooseTab.BAR_ONE;
                break;
            case TwoTabBar.TwoTabChooseTab.BAR_TWO:
                mCurrentTab = TwoTabBar.TwoTabChooseTab.BAR_TWO;
                break;
        }
        onRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void loadData(int pageNum, int pageSize, final boolean isRefresh) {

        if (isRefresh) {
            mCurrentPage = RestClient.DEFAULT_PAGE;
        }
        showProgressDialog();
        Call<SubjectListResponse> call;
        if (mCoursePickStorage != null) {
            if (!(mCoursePickStorage.getMinPrice().equals("0") && mCoursePickStorage.getMaxPrice().equals("3500"))) {
                call = MFPApplication.getInstance().getRestClient().getSubjectList(pageNum, pageSize, mCoursePickStorage.getMaxPrice(), mCoursePickStorage.getMinPrice(), mCoursePickStorage.getmEvaluateOrder() == -1 ? "" : mCoursePickStorage.getmEvaluateOrder() + "", mCoursePickStorage.getmCountOrder() == -1 ? "" : mCoursePickStorage.getmCountOrder() + "", "", "", "");
            } else {
                call = MFPApplication.getInstance().getRestClient().getSubjectList(pageNum, pageSize, "", "", mCoursePickStorage.getmEvaluateOrder() == -1 ? "" : mCoursePickStorage.getmEvaluateOrder() + "", mCoursePickStorage.getmCountOrder() == -1 ? "" : mCoursePickStorage.getmCountOrder() + "", "", "", "");
            }

        } else {
            call = MFPApplication.getInstance().getRestClient().getSubjectList(pageNum, pageSize, "", "", "", "", "", "", "");
        }
        call.enqueue(new Callback<SubjectListResponse>() {
            @Override
            public void onResponse(Call<SubjectListResponse> call, Response<SubjectListResponse> response) {
                dismissProgressDialog();
                if (response.body() != null && response.body().getData() != null) {

                    if (isRefresh) {
                        if (response.body().getData().size() > 0) {
                            mProductAdapter.refreshData(response.body().getData());
                            mHasMoreData = true;
                            mEmptyLayout.setVisibility(View.GONE);
                        } else {
                            mHasMoreData = false;
                            mProductAdapter.clearAll();
                            mEmptyLayout.setVisibility(View.VISIBLE);
                        }
                    } else {
                        if (response.body().getData().size() > 0) {
                            mHasMoreData = true;
                        } else {
                            mHasMoreData = false;
                        }
                        mProductAdapter.addAll(response.body().getData());
                    }

                }
            }

            @Override
            public void onFailure(Call<SubjectListResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

    @Override
    public void onRefresh() {
        mCurrentPage = RestClient.DEFAULT_PAGE;
        switch (mCurrentTab){
            case TwoTabBar.TwoTabChooseTab.BAR_ONE:
                loadData(mCurrentPage, RestClient.DEFAULT_PAGE_SIZE, true);
                break;
            case TwoTabBar.TwoTabChooseTab.BAR_TWO:
                getSchoolLive();
                break;
        }

        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
    }


    private void getSchoolLive() {
        showProgressDialog();
        Call<TeamListResponse> call = MFPApplication.getInstance().getRestClient().getClassGoodList(mCurrentPage);
        call.enqueue(new Callback<TeamListResponse>() {
            @Override
            public void onResponse(Call<TeamListResponse> call, Response<TeamListResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if(response.body().getData() != null && response.body().getData().size() > 0){
                        mEmptyLayout.setVisibility(View.GONE);
                        mHasMoreData = true;
                        if(mCurrentPage == RestClient.DEFAULT_PAGE){
                            mProductAdapter.refreshClassCourseData(response.body().getData());
                        }else{
                            mProductAdapter.addAllClassCourse(response.body().getData());
                        }
                        mProductAdapter.notifyDataSetChanged();
                    }else{
                        if(mCurrentPage == RestClient.DEFAULT_PAGE){
                            mProductAdapter.clearAllClassCourse();
                            mEmptyLayout.setVisibility(View.VISIBLE);
                        }
                        mHasMoreData = false;
                    }
                }

            }

            @Override
            public void onFailure(Call<TeamListResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

    @Override
    public void onLoad() {
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
        if(mHasMoreData){
            mCurrentPage ++;
            switch (mCurrentTab){
                case TwoTabBar.TwoTabChooseTab.BAR_ONE:
                    loadData(mCurrentPage, RestClient.DEFAULT_PAGE_SIZE, false);
                    break;
                case TwoTabBar.TwoTabChooseTab.BAR_TWO:
                    getSchoolLive();
                    break;
            }

        }


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        MFPApplication.getInstance().getEventController().removeUIEventListener(EventDispatcherEnum.UI_EVENT_COURSE_PICK, this);

    }

    @Override
    public void handleUIEvent(Message msg) {

        switch (msg.what) {
            case EventDispatcherEnum.UI_EVENT_COURSE_PICK:
                if(msg.arg1 == CoursePickActivity.FLAG_FROM_MAIN_TAB){
                    mCoursePickStorage = GsonUtil.fromJson(PreferencesStorageUtil.getCCoursePickSearchStr(getContext()), CoursePickActivity.CoursePickStorage.class);
                    loadData(RestClient.DEFAULT_PAGE, RestClient.DEFAULT_PAGE_SIZE, true);
                    mProductAdapter.setHeaderList(mCoursePickStorage.toHorizontalList());
                }
//                mHorizontalTagBar.initDataList(mCoursePickStorage.toHorizontalList());
                break;
        }
    }

}
